package cn.practice.chat.service.impl;

import cn.practice.chat.entity.User;
import cn.practice.chat.entity.UserFriend;
import cn.practice.chat.entity.UserPassword;
import cn.practice.chat.lang.RedisConst;
import cn.practice.chat.lang.Result;
import cn.practice.chat.mapper.UserFriendMapper;
import cn.practice.chat.mapper.UserMapper;
import cn.practice.chat.mapper.UserPasswordMapper;
import cn.practice.chat.request.regist.RegistRequest;
import cn.practice.chat.service.RegistService;
import cn.practice.chat.utils.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.UUID;

import static cn.practice.chat.lang.Const.userChatImage;

/**
 * @ClassName RegistServiceImpl
 * @Description:
 * @Author A-TAO
 * @Date 2022/11/3
 * @Version V1.0
 **/
@Slf4j
@Service
public class RegistServiceImpl implements RegistService {

    @Autowired
    private UserPasswordMapper userPasswordMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    @Autowired
    private UserFriendMapper userFriendMapper;


    @Autowired
    private RedisUtil redisUtil;


    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public Result userRegist(RegistRequest request) {
        log.info("新用户注册，{}", JSONObject.toJSONString(request));
        if(!request.getAgainpassword().equals(request.getPassword())){
            return Result.error("两次密码不一致");
        }
        // 查询账号是否已经存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", request.getUsername());
        List<User> users = userMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(users)){
            return Result.error("账号已经被人注册");
        }

        String password = passwordEncoder.encode(request.getPassword());

        UserPassword userPassword = new UserPassword();
        userPassword.setPassword(password);
        userPassword.setUsername(request.getUsername());
        userPasswordMapper.insert(userPassword);

        Integer userId = userPassword.getId();
        User user = new User();
        user.setUserId(userId);
        user.setUserCode(request.getUsername());
        user.setUsername(request.getUsername());
        user.setNick(request.getNick());
        user.setImageUrl(request.getUserImage());
        userMapper.insert(user);

        log.info("新用户注册成功，{}", JSONObject.toJSONString(user));
        return Result.success();
    }
}
